<?php

declare(strict_types=1);

namespace Phpben\Imi\Auth;

use Exception;
use Imi\Config;
use Phpben\Imi\Auth\Contract\TokenContract;

class AuthManager
{
    protected $config;
    protected $name;

    public function __construct(?string $name = null)
    {
        $this->name = $name ?? 'default';
        $this->config = Config::get('@app.beans.AuthConfig');
    }

    /**
     * @throws Exception
     */
    public function __call($name, $arguments)
    {
        $guard = $this->guard();
        if (method_exists($guard, $name)) {
            return call_user_func_array([$guard, $name], $arguments);
        }
        throw new Exception('Auth(' . $name . ') not defined.');
    }

    /**
     * @throws Exception
     */
    public function guard(?string $name = null): TokenContract
    {
        $name = $name ?: $this->name;
        if (!isset($this->config[$name])) {
            throw new Exception('AuthConfig(' . $name . ') not defined.');
        }
        $config = $this->config[$name];
        return new $config['auth']($config);
    }

    /**
     * 返回Auth实例
     * @param int|null $user_id 用户ID
     * @param string|null $name
     * @return Auth
     * @throws Exception
     */
    public function auth(?int $user_id = null, ?string $name = null): Auth
    {
        $name = $name ?: $this->name;
        if (!isset($this->config[$name])) {
            throw new Exception('AuthConfig(' . $name . ') not defined.');
        }
        $config = $this->config[$name];
        return Auth::instance($config)->setUserId($user_id ?? $this->guard()->user()->id);
    }
}
